import Vue from 'vue'
import global from '@/common/global.js'
var _bj_id=uni.getStorageSync('bj_id');
var _role=uni.getStorageSync('role');
var token=uni.getStorageSync('token');
var setUserCode=uni.getStorageSync('setUserCode');
var userId=uni.getStorageSync('userId');
var headImgUrl=uni.getStorageSync('headImgUrl');
var userName=uni.getStorageSync('userName');

const state = {
	token: "",
	name: userName,
	head: headImgUrl,
	cancel_login: false,
	introduction: '',
	roles: [],
	role: _role,
	sessionid: "",
	bj: "",
	rulelist: {},
	reurl: '',
	bj_list: [],
	bj_id: _bj_id,
	bj_name: '',
	jf: 0,
	system: [],
	zzConfig:{},
	nickName:userName,
	rules:'',
	uid:'',
	vipId:userId,
	mobile:'',
	Menu:[],
	xqlist:[]
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_INTRODUCTION: (state, introduction) => {
		state.introduction = introduction
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_HEAD: (state, avatar) => {
		state.head = avatar
	},
	SET_ROLES: (state, roles) => {
		state.roles = roles
	},
	SET_ROLE: (state, role) => {
		state.role = role
		uni.setStorageSync('role',role)
	},
	SET_SESSION: (state, sessionid) => {
		state.sessionid = sessionid
	},
	SET_BJ: (state, BJ) => {
		state.bj = BJ
	},
	SET_RULELIST: (state, RULELIST) => {
		state.rulelist = RULELIST
	},
	SET_REURL: (state, REURL) => {
		state.reurl = REURL
	},
	SET_BJLIST: (state, BJLIST) => {
		state.bj_list = BJLIST
	},
	SET_BJID: (state, BJID) => {
		state.bj_id = BJID
		uni.setStorageSync('bj_id',BJID)
	},
	SET_BJNAME: (state, NAME) => {
		state.bj_name = NAME
	},
	SET_JF: (state, JF) => {
		state.jf = JF
	},
	SET_SYSTEM: (state, system) => {
		state.system = system
	},
	SET_ZZCONFIG: (state, zzConfig) => {
		state.zzConfig = zzConfig
	},
	SET_NICKNAME:(state, name)=>{
		state.nickName = name
	},
	SET_RULES:(state, rels)=>{
		state.rules = rels
	},
	SET_UID:(state, id)=>{
		state.uid = id
	},
	SET_VIPID:(state, vid)=>{
		state.vipId = vid
	},
	SET_MOBILE: (state, mobile) => {
		state.mobile = mobile
	},
	SET_MENU:(state, menu) =>{
		state.Menu = menu
	},
	SET_XQLIST:(state, list) =>{
		state.xqlist = list
	},
	SET_CANCELLOGIN: (state, iscancellogin) =>{
		state.cancel_login = iscancellogin
	}
}

const actions = {
	// user login
	login({
		commit
	}, userInfo) {
		const {
			username,
			password
		} = userInfo
		return new Promise((resolve, reject) => {
			Vue.prototype.$http.post(Vue.prototype.$api.user.login,{
				username: username,
				password: password
			}).then(response => {
				const {
					data
				} = response
				
				commit('SET_SESSION', data.PHPSESSID)

				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
	checkRole({
		commit,
		dispatch
	}) {
		return new Promise((resolve, reject) => {
			if (!state.role) {
				uni.reLaunch({
					url: '/pages/user/login/change/change'
				});
			}
		})
	},
	checkLogin({
		commit,
		dispatch
	}) {
		return new Promise((resolve, reject) => {
			Vue.prototype.$http.post(Vue.prototype.$api.user.getInfo).then((re) => {

				commit("SET_NAME", re.data.nickname)
				commit("SET_HEAD", re.data.headimgurl)
				commit("SET_BJ", re.data.bj_name)

				commit("SET_RULELIST", {
					jz: re.data.jz,
					ls: re.data.ls
				})
				if(re.data.zzconfg){
					// console.log(re.data.zzconfg)
					commit("SET_ZZCONFIG", Object.assign({},re.data.zzconfg))
				}
				commit('SET_NICKNAME',re.data.nickname)
				commit('SET_RULES',re.data.rule)
				commit('SET_UID',re.data.uid)
				commit('SET_VIPID',re.data.vip)
				
				commit("SET_ROLES", re.data.ruleList)
				commit("SET_ROLE", re.data.rule)
				commit("SET_BJLIST", re.data.bj_list)
				commit("SET_BJID", re.data.bj_id)
				commit("SET_BJNAME", re.data.bj_name)
				
				commit("SET_SYSTEM",re.data.system)
				//手机号码
				if(re.data.mobile){
					commit("SET_MOBILE",re.data.mobile)
				}
				if(re.data.xq_list){
					commit("SET_XQLIST",re.data.xq_list)
				}
				
				
				
				if(re.data.rule=='jz'&&re.data.xs_id>0){
					let thisxs=re.data.jz.find(x=>x.xs_id==re.data.xs_id)
					if(thisxs&&thisxs.jf){
						commit("SET_JF", thisxs.jf)
					}
				}
				resolve()
			})
		})
	},
	reurl({
		commit,
		dispatch
	}) {
		return new Promise((resolve, reject) => {
			let gourl = '/pages/edu/select-class'
			if (state.reurl) {
				console.log("跳转store地址")
				gourl = "/"+state.reurl
				commit("SET_REURL", '')
			}
			uni.reLaunch({
				url: gourl
			})
		})
	},
	setSession({
		commit
	}, session) {
		return new Promise((resolve, reject) => {
			commit('SET_SESSION', session)

		})
	},
	setMenu({
		commit,
		dispatch
	}){
		return new Promise((resolve, reject) =>{
			Vue.prototype.$http.post(Vue.prototype.$api.user.menu).then(res=>{
				// console.log(res.data)
				commit('SET_MENU',res.data)
			})
		})
	},
	// get class info
	autoclass({
		commit,
		dispatch
	}){
		return new Promise((resolve,reject)=>{
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			if(page&&page.route&&page.route!='pages/user/login/registerstudent/registerstudent'){
				commit("SET_REURL", page.route)
			}
			uni.navigateTo({
				url: '/pages/user/login/registerstudent/registerstudent'
			});
			
		})
	},
	// get user info
	autologin({
		commit,
		dispatch
	}) {
		return new Promise((resolve, reject) => {
			return
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			console.log('开始自动登录',page)
			if(page&&page.route&&page.route!='pages/user/login/login'){
				commit("SET_REURL", page.route)
			}else{
				console.log('当前已经是登录页面了',page)
				return;
			}
			//H5和微信公众号
			// #ifdef H5
			var ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/micromessenger/i) == 'micromessenger') {
				window.location = global.baseUrl + "Wx/getUser&reurl=" +  encodeURIComponent(window.location.href)
			} else {
				if(state.cancel_login == false) {
					uni.showModal({
						title: '温馨提示',
						showCancel:false,
						content: '您还没有登录,请先授权登录!',
						confirmColor: '#1CBBB4',
						success: async (res) => {
							if (res.confirm) {
								uni.reLaunch({
									url: '/pages/user/login/login'
								});
							} else {
								commit('SET_CANCELLOGIN',true);
							}
						}
					});
				}
			}
			// #endif

			//APP
			// #ifdef APP-PLUS || MP
			console.log("自动登录===》",state.cancel_login)
			if(state.cancel_login == false) {
				console.log("弹窗")
				
				uni.reLaunch({
					url: '/pages/user/login/login'
				});
				
				// uni.showModal({
				// 	title: '温馨提示',
				// 	content: '您还没有登录,请先授权登录!',
				// 	confirmColor: '#1CBBB4',
				// 	cancelText: '取消不再提示',
				// 	success: (res) => {
				// 		if (res.confirm) {
				// 			uni.reLaunch({
				// 				url: '/pages/user/login/login'
				// 			});
				// 		} else {
				// 			commit('SET_CANCELLOGIN',true);
				// 		}
				// 	}
				// });
			}
			// #endif


		})
	},

	// user logout
	logout({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			Vue.prototype.$http.post(Vue.prototype.$api.logoutUrl).then(() => {
				commit('SET_TOKEN', '')
				commit('SET_ROLES', [])
				resetRouter()
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
	// Dynamically modify permissions
	changeRoles({
		commit,
		dispatch
	}, role) {
		return new Promise(async resolve => {
			const token = role + '-token'

			commit('SET_TOKEN', token)

			const {
				roles
			} = await dispatch('getInfo')

			resetRouter()

			// generate accessible routes map based on roles
			const accessRoutes = await dispatch('permission/generateRoutes', roles, {
				root: true
			})

			// dynamically add accessible routes
			router.addRoutes(accessRoutes)

			resolve()
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
